package com.heze.xunhuan.controller;

import com.heze.xunhuan.dto.PostCreateDTO;
import com.heze.xunhuan.service.PostService;
import com.heze.xunhuan.utils.SecurityContextUtil;
import com.heze.xunhuan.vo.PageVO;
import com.heze.xunhuan.vo.PostVO;
import com.heze.xunhuan.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 信息控制器
 *
 * @author heze-xunhuan
 */
@Tag(name = "信息管理", description = "信息发布和浏览相关接口")
@RestController
@RequestMapping("/api/v1/posts")
@RequiredArgsConstructor
public class PostController {

    private final PostService postService;

    @Operation(summary = "发布信息", description = "发布一条新信息")
    @PostMapping
    public Result<Long> createPost(
            @RequestParam(required = false) Integer categoryId,
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam(required = false) String mediaType,
            @RequestParam(required = false) MultipartFile[] mediaFiles) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.unauthorized("未登录");
        }

        PostCreateDTO dto = buildPostCreateDTO(categoryId, title, content, mediaType, mediaFiles);
        Long postId = postService.createPost(userId, dto);
        return Result.success(postId);
    }

    @Operation(summary = "更新信息", description = "更新已发布的信息")
    @PutMapping("/{id}")
    public Result<Void> updatePost(
            @PathVariable Long id,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam(required = false) String mediaType,
            @RequestParam(required = false) MultipartFile[] mediaFiles) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.unauthorized("未登录");
        }

        PostCreateDTO dto = buildPostCreateDTO(categoryId, title, content, mediaType, mediaFiles);
        postService.updatePost(userId, id, dto);
        return Result.success();
    }

    @Operation(summary = "删除信息", description = "删除已发布的信息")
    @DeleteMapping("/{id}")
    public Result<Void> deletePost(@PathVariable Long id) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.unauthorized("未登录");
        }
        postService.deletePost(userId, id);
        return Result.success();
    }

    @Operation(summary = "获取信息详情", description = "获取信息的详细信息")
    @GetMapping("/{id}")
    public Result<PostVO> getPostDetail(@PathVariable Long id) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        PostVO postVO = postService.getPostDetail(id, userId);
        return Result.success(postVO);
    }

    @Operation(summary = "信息瀑布流", description = "分页获取信息列表")
    @GetMapping("/feed")
    public Result<PageVO<PostVO>> getPostFeed(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String subCategory,
            @RequestParam(required = false) Double lat,
            @RequestParam(required = false) Double lng,
            @RequestParam(required = false) Double radius,
            @RequestParam(required = false) String sortBy) {
        PageVO<PostVO> pageVO = postService.getPostPage(page, size, categoryId, subCategory,
                lat, lng, radius, sortBy);
        return Result.success(pageVO);
    }

    @Operation(summary = "搜索信息", description = "根据关键词搜索信息")
    @GetMapping("/search")
    public Result<PageVO<PostVO>> searchPosts(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice) {
        PageVO<PostVO> pageVO = postService.searchPosts(page, size, keyword, categoryId, minPrice, maxPrice);
        return Result.success(pageVO);
    }

    @Operation(summary = "获取我的发布", description = "获取当前用户发布的信息列表")
    @GetMapping("/my")
    public Result<PageVO<PostVO>> getMyPosts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String status) {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.unauthorized("未登录");
        }
        PageVO<PostVO> pageVO = postService.getMyPosts(userId, page, size, status);
        return Result.success(pageVO);
    }

    @Operation(summary = "记录浏览", description = "记录信息浏览次数")
    @PostMapping("/{id}/view")
    public Result<Void> recordView(@PathVariable Long id) {
        postService.recordView(id);
        return Result.success();
    }

    @Operation(summary = "获取发布限制", description = "获取用户发布数量限制信息")
    @GetMapping("/limit")
    public Result<Object> getPostLimit() {
        Long userId = SecurityContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.unauthorized("未登录");
        }
        Object limit = postService.getPostLimit(userId);
        return Result.success(limit);
    }

    /**
     * 构建PostCreateDTO对象
     */
    private PostCreateDTO buildPostCreateDTO(Integer categoryId, String title, String content,
                                             String mediaType, MultipartFile[] mediaFiles) {
        PostCreateDTO dto = new PostCreateDTO();
        dto.setCategoryId(categoryId);
        dto.setTitle(title);
        dto.setContent(content);
        dto.setMediaType(mediaType);

        if (mediaFiles != null && mediaFiles.length > 0) {
            List<MultipartFile> fileList = new ArrayList<>();
            for (MultipartFile file : mediaFiles) {
                if (!file.isEmpty()) {
                    fileList.add(file);
                }
            }
            dto.setMediaFiles(fileList);
        }

        return dto;
    }
}